<?php
// +----------------------------------------------------------------------
// | DTPHP 
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://dtphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yyj <qingchen.yyj@gmail.com>
// +----------------------------------------------------------------------


namespace app\admin\controller;


use app\admin\model\UpmsPermission;
use app\admin\model\UpmsRole;
use app\admin\model\UpmsRolePermission;
use app\admin\model\UpmsUser;
use app\admin\model\UpmsUserPermission;
use app\common\base\BaseController;
use app\common\utils\Tools;
use think\Db;

class Permission extends BaseController
{
    public $table = 'UpmsPermission';


    /**
     * @return array|string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $list = (new UpmsPermission())->order('permission_id asc,pid asc')->select();
        $list = Tools::buildArrFromObj($list);
        $list = formatTree(listToTree($list));
        return $this->buildSuccess($list);
    }


    /**
     * @return array
     */
    public function save()
    {
        $this->requestType('POST');
        $permission['permission_id'] = $this->request->param('id');
        $permission['name'] = $this->request->param('name');
        $permission['uri'] = $this->request->param('uri');
        $permission['pid'] = $this->request->param('pid');
        if ($permission['permission_id'] != 0) {
            UpmsPermission::update($permission);
            return $this->buildSuccess([]);
        } else if (UpmsPermission::create($permission)) {
            return $this->buildSuccess([]);
        }

        return $this->buildFailed();
    }

    /**
     * @return array
     * @throws \think\exception\DbException
     */
    public function read()
    {
        $roleId = $this->request->get('id', 0);

        $list = (new UpmsPermission())->order('permission_id asc,pid asc')->select();
        $list = Tools::buildArrFromObj($list);
        $list = listToTree($list);

        $rules = [];
        if ($roleId) {
            $rules = (new UpmsRolePermission())->where(['role_id' => $roleId])->select();
            $rules = Tools::buildArrFromObj($rules);
            $rules = array_column($rules, 'permission_id');
        }
        $newList = $this->buildList($list, $rules);

        return $this->buildSuccess($newList);

    }

    /**
     * @return array
     * @throws \think\exception\DbException
     */
    public function readUser()
    {
        $userId = $this->request->get('id', 0);
        $havedRoles = UpmsUser::get($userId)->upmsUserRoles;
        $havedPermissions = [];
        foreach ($havedRoles as $havedRole) {
            $havedPermissions = array_merge($havedPermissions, UpmsRole::get($havedRole['role_id'])->upmsRolePermissions);
        }
        $list = (new UpmsPermission())->order('permission_id asc,pid asc')->select();
        foreach ($havedPermissions as $havedPermission) {
            foreach ($list as $key => $item) {
                if ($havedPermission['permission_id'] == $item['permission_id']) {
                    unset($list[$key]);
                }
            }
        }
        $list = Tools::buildArrFromObj($list);
        $list = listToTree($list);

        $rules = [];
        if ($userId) {
            $rules = (new UpmsUserPermission())->where(['user_id' => $userId])->select();
            $rules = Tools::buildArrFromObj($rules);
            $rules = array_column($rules, 'permission_id');
        }
        $newList = $this->buildList($list, $rules);

        return $this->buildSuccess($newList);

    }

    /**
     * 构建适用前端的权限数据
     * @param $list
     * @param $rules
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    private function buildList($list, $rules)
    {
        $newList = [];
        foreach ($list as $key => $value) {
            $newList[$key]['title'] = $value['name'];
            $newList[$key]['key'] = $value['permission_id'];
            if (isset($value['_child'])) {
                $newList[$key]['expand'] = true;
                $newList[$key]['children'] = $this->buildList($value['_child'], $rules);
            } else {
                if (in_array($value['permission_id'], $rules)) {
                    $newList[$key]['checked'] = true;
                }
            }
        }

        return $newList;
    }


    public function change()
    {
        $permission['permission_id'] = $this->request->param('id');
        //异或取反
        $permission['status'] = $this->request->param('status') ^ 1;
        if (UpmsPermission::update($permission)) {
            return $this->buildSuccess([]);
        }
        return $this->buildFailed();

    }

    public function delete()
    {
        $this->requestType('POST');
        $permission_id = $this->request->param('id');
        if (UpmsPermission::destroy($permission_id)) {
            UpmsPermission::destroy(['pid' => $permission_id]);
            return $this->buildSuccess([]);
        }
        return $this->buildFailed();
    }

}